<?php 
/*
 * This filter convert simple array to tree array
 * and sort it
 *  
 */
class Zen_Filter_ArrayToTree
{
    protected $dbdata;
    protected $data;
    protected $map;
	protected $id='id';
	protected $parent_id='parent_id';
	protected $children='children';
	protected $order='order';
    
	public function setId($id){
		$this->id=$id;
	}
	public function setParentId($ParentId){
		$this->ParentId=$ParentId;
	} 
	
	public function setChildren($children){
		$this->children=$children;
	}
	public function setOrder($order){
		$this->order=$order;
	}
	
	public function getId(){
		return ($this->id);
	}
	public function getParentId(){
		return ($this->ParentId);
	} 
	
	public function getChildren(){
		return ($this->children);
	}
	public function getOrder(){
		return ($this->order);
	}
	
	
	
    private function mapArray(){
        foreach ($this->dbdata as $arr) {
            $order=$arr[$this->order];
            while (isset( $this->map[$arr[$this->parent_id]][$order])){
            $order++;
            }
            $this->map[$arr[$this->parent_id]][$order] = $arr[$this->id];
            $this->data[$arr[$this->id]] = $arr;
        }
        
        foreach ($this->map as $key=>$value ){
            ksort($value);
            $this->map[$key]=$value;
        }
    }
    
    private function fillarray ($node = 0, $level)
    {
        $nodes=array();
        foreach ($this->map[$node] as $key=>$child) {
            $node=$this->data[$child];
            if (isset($this->map[$child])) {
               $node[$this->children]=$this->fillarray($child, $level + 1);
            }
            $nodes[]=$node;
        }
        return $nodes;
    }
    
    public function filter($data){
    	$this->dbdata=$data;
    	$this->mapArray();
    	$res=$this->fillarray('0',1);
    	return $res;
    }
}